package com.wuyou.securitydemo.pwd;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyou.securitydemo.component.ResourceAuthExceptionEntryPoint;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * WebSecurityConfigurerAdapter
 *
 * @Date 2025/4/7 15:30
 * @Author 无忧
 */
@Getter
@Setter
public class CustomizedPasswordSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private AuthenticationSuccessHandler customizedAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationEventPublisher defaultAuthenticationEventPublisher;
    @Autowired
    private UserDetailsService customizedUserDetailsService;
    @Autowired
    private AuthenticationUserDetailsService authenticationUserDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        CustomizedPasswordAuthenticationProcessingFilter filter = new CustomizedPasswordAuthenticationProcessingFilter();
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter.setAuthenticationSuccessHandler(customizedAuthenticationSuccessHandler);
        filter.setEventPublisher(defaultAuthenticationEventPublisher);
        filter.setAuthExceptionEntryPoint(new ResourceAuthExceptionEntryPoint(objectMapper));


        CustomizedPasswordAuthenticationProvider provider = new CustomizedPasswordAuthenticationProvider();
        provider.setUserDetailsService(customizedUserDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
//        provider.setTokenService(authenticationUserDetailsService);
//        provider.setPermitAdminLoginProperties(permitAdminLoginProperties);
        http.authenticationProvider(provider)
                .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
